package xyz.goodcloud.file_open;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.NonNull;
import android.content.Context;
import android.content.Intent;
import android.app.Activity;
import android.util.Log;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import android.content.ActivityNotFoundException;
import java.io.File;
import androidx.core.content.FileProvider;
/** FileOpenPlugin */
public class FileOpenPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;
  private Context context;
  private Activity activity;
  private Result result;
  private String filePath;
  private String typeString;
  private static final String TYPE_STRING_APK = "application/vnd.android.package-archive";

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "xyx/file_open");
    context = flutterPluginBinding.getApplicationContext();
    channel.setMethodCallHandler(this);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result _result) {
    
    if (call.method.equals("open_file")) {
      filePath = call.argument("path");
      result = _result;
      typeString = getFileType(filePath);
      startActivity();
    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }
    private void startActivity() {
        File file = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (TYPE_STRING_APK.equals(typeString))
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        else
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addCategory("android.intent.category.DEFAULT");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            String packageName = context.getPackageName();
            Uri uri = FileProvider.getUriForFile(context,packageName + ".xyz.goodcloud.file_open.fileProvider", new File(filePath));
            intent.setDataAndType(uri, typeString);
        } else {
            intent.setDataAndType(Uri.fromFile(file), typeString);
        }
        Log.v("1","111");
        int type = 0;
        String message = "done";
        try {
            activity.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            type = -1;
            message = "No APP found to open this file。";
            Log.v("1",message);
        } catch (Exception e) {
            type = -2;
            message = "File opened incorrectly。";
            Log.v("1",message);
        }
        result.success(type);
    }

    private String getFileType(String filePath) {
      String[] fileStrs = filePath.split("\\.");
      String fileTypeStr = fileStrs[fileStrs.length - 1].toLowerCase();
      switch (fileTypeStr) {
          case "3gp":
              return "video/3gpp";
          case "torrent":
              return "application/x-bittorrent";
          case "kml":
              return "application/vnd.google-earth.kml+xml";
          case "gpx":
              return "application/gpx+xml";
          case "apk":
              return TYPE_STRING_APK;
          case "asf":
              return "video/x-ms-asf";
          case "avi":
              return "video/x-msvideo";
          case "bin":
          case "class":
          case "exe":
              return "application/octet-stream";
          case "bmp":
              return "image/bmp";
          case "c":
              return "text/plain";
          case "conf":
              return "text/plain";
          case "cpp":
              return "text/plain";
          case "doc":
              return "application/msword";
          case "docx":
              return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
          case "xls":
          case "csv":
              return "application/vnd.ms-excel";
          case "xlsx":
              return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
          case "gif":
              return "image/gif";
          case "gtar":
              return "application/x-gtar";
          case "gz":
              return "application/x-gzip";
          case "h":
              return "text/plain";
          case "htm":
              return "text/html";
          case "html":
              return "text/html";
          case "jar":
              return "application/java-archive";
          case "java":
              return "text/plain";
          case "jpeg":
              return "image/jpeg";
          case "jpg":
              return "image/jpeg";
          case "js":
              return "application/x-javascript";
          case "log":
              return "text/plain";
          case "m3u":
              return "audio/x-mpegurl";
          case "m4a":
              return "audio/mp4a-latm";
          case "m4b":
              return "audio/mp4a-latm";
          case "m4p":
              return "audio/mp4a-latm";
          case "m4u":
              return "video/vnd.mpegurl";
          case "m4v":
              return "video/x-m4v";
          case "mov":
              return "video/quicktime";
          case "mp2":
              return "audio/x-mpeg";
          case "mp3":
              return "audio/x-mpeg";
          case "mp4":
              return "video/mp4";
          case "mpc":
              return "application/vnd.mpohun.certificate";
          case "mpe":
              return "video/mpeg";
          case "mpeg":
              return "video/mpeg";
          case "mpg":
              return "video/mpeg";
          case "mpg4":
              return "video/mp4";
          case "mpga":
              return "audio/mpeg";
          case "msg":
              return "application/vnd.ms-outlook";
          case "ogg":
              return "audio/ogg";
          case "pdf":
              return "application/pdf";
          case "png":
              return "image/png";
          case "pps":
              return "application/vnd.ms-powerpoint";
          case "ppt":
              return "application/vnd.ms-powerpoint";
          case "pptx":
              return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
          case "prop":
              return "text/plain";
          case "rc":
              return "text/plain";
          case "rmvb":
              return "audio/x-pn-realaudio";
          case "rtf":
              return "application/rtf";
          case "sh":
              return "text/plain";
          case "tar":
              return "application/x-tar";
          case "tgz":
              return "application/x-compressed";
          case "txt":
              return "text/plain";
          case "wav":
              return "audio/x-wav";
          case "wma":
              return "audio/x-ms-wma";
          case "wmv":
              return "audio/x-ms-wmv";
          case "wps":
              return "application/vnd.ms-works";
          case "xml":
              return "text/plain";
          case "z":
              return "application/x-compress";
          case "zip":
              return "application/x-zip-compressed";
          default:
              return "*/*";
      }
  }

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        activity = binding.getActivity();
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {

    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {

    }

    @Override
    public void onDetachedFromActivity() {

    }
}
